// 浏览器状态管理
class BrowserManager {
    constructor() {
        this.tabs = [];
        this.activeTabIndex = 0;
        this.tabCounter = 0;
        this.init();
    }

    init() {
        this.setupEventListeners();
        this.setupElectronAPI();
        this.createInitialTab();
        this.updateUI();
    }

    setupEventListeners() {
        // 工具栏按钮事件
        document.getElementById('backBtn').addEventListener('click', () => this.goBack());
        document.getElementById('forwardBtn').addEventListener('click', () => this.goForward());
        document.getElementById('reloadBtn').addEventListener('click', () => this.reload());
        document.getElementById('homeBtn').addEventListener('click', () => this.goHome());
        document.getElementById('newTabBtn').addEventListener('click', () => this.createNewTab());
        document.getElementById('closeTabBtn').addEventListener('click', () => this.closeCurrentTab());
        document.getElementById('goBtn').addEventListener('click', () => this.navigate());

        // 地址栏事件
        document.getElementById('addressBar').addEventListener('keypress', (e) => {
            if (e.key === 'Enter') {
                this.navigate();
            }
        });

        // 键盘快捷键
        document.addEventListener('keydown', (e) => {
            if (e.ctrlKey || e.metaKey) {
                switch (e.key) {
                    case 't':
                        e.preventDefault();
                        this.createNewTab();
                        break;
                    case 'w':
                        e.preventDefault();
                        this.closeCurrentTab();
                        break;
                    case 'r':
                        e.preventDefault();
                        this.reload();
                        break;
                    case 'l':
                        e.preventDefault();
                        document.getElementById('addressBar').focus();
                        break;
                }
            }
        });
    }

    setupElectronAPI() {
        // 监听主进程消息
        if (window.electronAPI) {
            window.electronAPI.onNewTab(() => this.createNewTab());
            window.electronAPI.onCloseTab(() => this.closeCurrentTab());
        }

        // 显示版本信息
        this.showVersion();
    }

    async showVersion() {
        if (window.electronAPI) {
            try {
                const version = await window.electronAPI.getAppVersion();
                document.getElementById('versionText').textContent = `v${version}`;
            } catch (error) {
                console.log('无法获取版本信息');
            }
        }
    }

    createInitialTab() {
        this.createNewTab('https://www.baidu.com');
    }

    createNewTab(url = 'https://www.baidu.com') {
        const tabId = ++this.tabCounter;
        const tab = {
            id: tabId,
            title: '新标签页',
            url: url,
            webview: null
        };

        this.tabs.push(tab);
        this.activeTabIndex = this.tabs.length - 1;

        this.createTabElement(tab);
        this.createWebview(tab);
        this.updateUI();
    }

    createTabElement(tab) {
        const tabList = document.getElementById('tabList');
        const tabElement = document.createElement('div');
        tabElement.className = 'tab';
        tabElement.dataset.tabId = tab.id;

        tabElement.innerHTML = `
            <span class="tab-title">${tab.title}</span>
            <button class="tab-close" onclick="browserManager.closeTab(${tab.id})">×</button>
        `;

        tabElement.addEventListener('click', (e) => {
            if (!e.target.classList.contains('tab-close')) {
                this.switchToTab(tab.id);
            }
        });

        tabList.appendChild(tabElement);
    }

    createWebview(tab) {
        const contentArea = document.querySelector('.content-area');

        // 移除现有的webview
        const existingWebview = contentArea.querySelector('webview');
        if (existingWebview) {
            existingWebview.style.display = 'none';
        }

        // 创建新的webview
        const webview = document.createElement('webview');
        webview.id = `webview-${tab.id}`;
        webview.src = tab.url;
        webview.style.display = 'none';

        // 设置webview属性
        webview.setAttribute('webpreferences', 'nodeIntegration=no, contextIsolation=yes');
        webview.setAttribute('allowpopups', 'true');
        webview.setAttribute('websecurity', 'false');

        // 事件监听
        webview.addEventListener('did-start-loading', () => {
            this.updateStatus('正在加载...');
            this.updateTabTitle(tab.id, '加载中...');
        });

        webview.addEventListener('did-stop-loading', () => {
            this.updateStatus('就绪');
        });

        webview.addEventListener('page-title-updated', (e) => {
            this.updateTabTitle(tab.id, e.title);
        });

        webview.addEventListener('did-navigate', (e) => {
            this.updateTabUrl(tab.id, e.url);
            this.updateAddressBar(e.url);
        });

        webview.addEventListener('did-navigate-in-page', (e) => {
            this.updateTabUrl(tab.id, e.url);
            this.updateAddressBar(e.url);
        });

        // 等待webview加载完成
        webview.addEventListener('dom-ready', () => {
            console.log(`Webview ${tab.id} 已准备就绪`);
            // 自动打开webview的开发者工具，方便调试iframe和页面内部console.log
            // webview.openDevTools();
        });

        // did-frame-finish-load事件：递归设置所有iframe（包括shadow-root内）的高度为100
        webview.addEventListener('did-frame-finish-load', () => {
            webview.shadowRoot.querySelectorAll('iframe').forEach(function (iframe) {
                iframe.style.transition = 'height 0.3s cubic-bezier(0.4,0,0.2,1)';
                iframe.style.setProperty('height', '100%', 'important');
            });
        });

        contentArea.appendChild(webview);
        tab.webview = webview;

        // 如果是当前标签页，显示webview
        if (this.tabs.indexOf(tab) === this.activeTabIndex) {
            webview.style.display = 'block';
        }
    }

    switchToTab(tabId) {
        const tabIndex = this.tabs.findIndex(tab => tab.id === tabId);
        if (tabIndex === -1) return;

        this.activeTabIndex = tabIndex;
        this.updateUI();
    }

    closeTab(tabId) {
        const tabIndex = this.tabs.findIndex(tab => tab.id === tabId);
        if (tabIndex === -1) return;

        // 如果只有一个标签页，创建新标签页
        if (this.tabs.length === 1) {
            this.createNewTab();
        }

        // 移除标签页
        this.tabs.splice(tabIndex, 1);

        // 移除DOM元素
        const tabElement = document.querySelector(`[data-tab-id="${tabId}"]`);
        if (tabElement) {
            tabElement.remove();
        }

        // 移除webview
        const webview = document.getElementById(`webview-${tabId}`);
        if (webview) {
            webview.remove();
        }

        // 调整活动标签页索引
        if (this.activeTabIndex >= tabIndex) {
            this.activeTabIndex = Math.max(0, this.activeTabIndex - 1);
        }

        this.updateUI();
    }

    closeCurrentTab() {
        if (this.tabs.length > 0) {
            this.closeTab(this.tabs[this.activeTabIndex].id);
        }
    }

    updateUI() {
        // 更新标签页状态
        document.querySelectorAll('.tab').forEach((tabElement, index) => {
            const tabId = parseInt(tabElement.dataset.tabId);
            const tab = this.tabs.find(t => t.id === tabId);

            if (tab && this.tabs.indexOf(tab) === this.activeTabIndex) {
                tabElement.classList.add('active');
            } else {
                tabElement.classList.remove('active');
            }
        });

        // 更新webview显示
        this.tabs.forEach((tab, index) => {
            if (tab.webview) {
                tab.webview.style.display = (index === this.activeTabIndex) ? 'block' : 'none';
            }
        });

        // 更新地址栏
        if (this.tabs.length > 0 && this.activeTabIndex < this.tabs.length) {
            const activeTab = this.tabs[this.activeTabIndex];
            this.updateAddressBar(activeTab.url);
        }

        // 更新按钮状态
        this.updateButtonStates();
    }

    updateButtonStates() {
        if (this.tabs.length === 0) return;

        const activeTab = this.tabs[this.activeTabIndex];
        if (!activeTab.webview) return;

        // 更新后退/前进按钮状态
        try {
            document.getElementById('backBtn').disabled = !activeTab.webview.canGoBack();
            document.getElementById('forwardBtn').disabled = !activeTab.webview.canGoForward();
        } catch (error) {
            console.log('更新按钮状态时出错:', error);
        }
    }

    updateTabTitle(tabId, title) {
        const tab = this.tabs.find(t => t.id === tabId);
        if (tab) {
            tab.title = title;
            const tabElement = document.querySelector(`[data-tab-id="${tabId}"] .tab-title`);
            if (tabElement) {
                tabElement.textContent = title;
            }
        }
    }

    updateTabUrl(tabId, url) {
        const tab = this.tabs.find(t => t.id === tabId);
        if (tab) {
            tab.url = url;
        }
    }

    updateAddressBar(url) {
        document.getElementById('addressBar').value = url;
    }

    updateStatus(message) {
        document.getElementById('statusText').textContent = message;
    }

    navigate() {
        if (this.tabs.length === 0) return;

        const url = document.getElementById('addressBar').value.trim();
        if (!url) return;

        let fullUrl = url;
        if (!url.startsWith('http://') && !url.startsWith('https://')) {
            // 检查是否是搜索查询
            if (url.includes('.') && !url.includes(' ')) {
                fullUrl = 'https://' + url;
            } else {
                fullUrl = `https://www.baidu.com/s?wd=${encodeURIComponent(url)}`;
            }
        }

        const activeTab = this.tabs[this.activeTabIndex];
        if (activeTab && activeTab.webview) {
            try {
                activeTab.webview.loadURL(fullUrl);
                console.log('正在导航到:', fullUrl);
            } catch (error) {
                console.error('导航失败:', error);
            }
        }
    }

    goBack() {
        const activeTab = this.tabs[this.activeTabIndex];
        if (activeTab && activeTab.webview && activeTab.webview.canGoBack()) {
            try {
                activeTab.webview.goBack();
                console.log('后退');
            } catch (error) {
                console.error('后退失败:', error);
            }
        }
    }

    goForward() {
        const activeTab = this.tabs[this.activeTabIndex];
        if (activeTab && activeTab.webview && activeTab.webview.canGoForward()) {
            try {
                activeTab.webview.goForward();
                console.log('前进');
            } catch (error) {
                console.error('前进失败:', error);
            }
        }
    }

    reload() {
        const activeTab = this.tabs[this.activeTabIndex];
        if (activeTab && activeTab.webview) {
            try {
                activeTab.webview.reload();
                console.log('刷新');
            } catch (error) {
                console.error('刷新失败:', error);
            }
        }
    }

    goHome() {
        this.navigateToUrl('https://www.baidu.com');
    }

    navigateToUrl(url) {
        const activeTab = this.tabs[this.activeTabIndex];
        if (activeTab && activeTab.webview) {
            try {
                activeTab.webview.loadURL(url);
                console.log('导航到:', url);
            } catch (error) {
                console.error('导航失败:', error);
            }
        }
    }
}

// 初始化浏览器
const browserManager = new BrowserManager(); 